//reload刷新页面，
//newLoad获取最新数据并刷新页面
//getAllusers获取用户信息
//delOneusers删除一个用户订单信息
import '@css/adminPage.css'

window.addEventListener("DOMContentLoaded", async () => {

  newLoad()
  // document.querySelector("#rightList").innerHTML
  document.querySelector("#rightTop").innerHTML = `
  <p id="searchuserBox">请输入用户名进行搜索<input id="searchUserBox"><button id="searchuserBtn">点击搜索</button></p>
  <div id="adduserBox"><button id="adduserBtn">+新增一个用户申请</button></div>
  `
})

//用户页面专属所用
document.querySelector("body").addEventListener("click", async (e) => {
  // 删除单个保单
  if (e.target.className == "userdelete") {
   await delOneUsers(e.target.parentElement.parentElement.firstElementChild.innerHTML)
    newLoad()
  }

  
  // 修改单个保单
  if (e.target.className == "usermodify") {
    //渲染页面
   await modifyUser(e.target.parentElement.parentElement.firstElementChild.innerHTML)
  }
  if (e.target.id == "makeSureModifyuser") {
    const result = await modifyContent()
    alert("修改成功")
    newLoad()
  }

  //模糊搜索事件绑定
  if (e.target.id == "searchuserBtn") {
    let content = document.querySelector("#searchUserBox").value
    const { rows } = await searchuser(content)

    let newArr = rows.filter(item => {
      return !item.delete
    })
    reload(newArr)
  }

  //增加功能区
  if (e.target.id == "adduserBtn") {
    //渲染增加页面
    adduserFirst()
  }

  //确认增加按钮
  if (e.target.id == "makeSureAdduser") {
    const result = await adduserContent()
    alert("增加成功")
    newLoad()
  }

  //取消执行操作按钮
  if (e.target.id == "canceluser") {
    newLoad()
  }
 

  //跳转到首页
  if (e.target.className == "title") {
    window.location.href = "adminPage.html"
  } 
  //审核#userdetail
})

//审核内容第一步，先渲染页面

//增加一个用户订单流程,第一步渲染
const adduserFirst = async () => {

  document.querySelector("#rightList").innerHTML =
  `
  <table id="userModifyTable">
<tr><td>客户姓名</td><td><input id="nameuserInput" ></td></tr>
<tr><td>登陆账号</td><td><input id="userAccountInput" ></td></tr>
<tr><td>联系电话</td><td><input id="userPhoneInput" ></td></tr>
<tr><td>登陆密码</td><td><input id="userPwdInput"></td></tr> 
<tr><td>负责销售员</td><td><input id="sellersInput" type="select"></td></tr>
<tr><td>创建时间</td><td><input  disabled="disabled" value="${new Date()}"></td></tr>
<tr><td></td><td><button id="makeSureAdduser">确认增加</button><button id="canceluser">取消</button></td></tr>
  `
}
//第二步，获取内容并提交申请
export const adduserContent = async () => {
  
  let userName = document.querySelector("#nameuserInput").value
  let userAccount = document.querySelector("#userAccountInput").value
  let userPhone = document.querySelector("#userPhoneInput").value

  let userPassWord = document.querySelector("#userPwdInput").value
  let sellersId = document.querySelector("#sellersInput").value
  //在后端转译代码

  let arr = { userName, userAccount, userPhone, userPassWord,sellersId}

  const result = await adduserReal(arr)
  //传输数据
  console.log(result);
}

document.querySelectorAll("h3").forEach(item => {
  item.addEventListener("click", async () => {
    if (item.style.backgroundColor != "gray") {
      item.style.backgroundColor = "gray"
      item.style.color = "white"
    } else {
      item.style.backgroundColor = "#485069"
      item.style.color = "rgb(175, 175, 175)"

    }
  })
})

//修改    页面之第一步渲染，点击传入_id，获取对应信息，然后渲染页面
//检查完毕
export const modifyUser = async (itemID) => {

  let { rows } = await getOneUser(itemID)
  let item = rows
  console.log(item);

  document.querySelector("#rightList").innerHTML =
    `
    <table id="userModifyTable">
  <tr><td>编号</td><td id="userID">${item._id}</td></tr>
  <tr><td>客户姓名</td><td><input id="nameuserInput" value="${item.userName}"></td></tr>
  <tr><td>登陆账号</td><td><input id="userAccountInput" value="${item.userAccount}"></td></tr>
  <tr><td>联系电话</td><td><input id="userPhoneInput" value="${item.userPhone}"></td></tr>
  <tr><td>登陆密码</td><td><input id="userPwdInput" value="${item.userPassWord}"></td></tr> 
  <tr><td>负责销售员</td><td><input id="sellersInput" type="select" value="${item.sellersId.sellersName}"></td></tr>
  <tr><td>修改时间</td><td><input  disabled="disabled" value="${new Date()}"></td></tr>
  <tr><td></td><td><button id="makeSureModifyuser">确认修改</button><button id="canceluser">取消</button></td></tr>
    `
}

//修改页面第二步 审查完毕，还差复选框没做 审查完毕
export const modifyContent = async () => {

  let _id = document.querySelector("#userID").innerHTML
  let userName = document.querySelector("#nameuserInput").value
  let userAccount = document.querySelector("#userAccountInput").value
  let userPhone = document.querySelector("#userPhoneInput").value

  let userPassWord = document.querySelector("#userPwdInput").value
  let sellersId = document.querySelector("#sellersInput").value
  //在后端转译代码

  let arr = { _id,userName, userAccount, userPhone, userPassWord,sellersId}
  console.log(arr);
  const result = await modifyuserReal(arr)
  //传输数据
  console.log(result);
}

//增加一个用户订单Api 审查完毕
const adduserReal = (arr) => {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    xhr.open("POST", "http://127.0.0.1:3000/users/addUser", true)
    xhr.setRequestHeader("content-type", "application/json")
    // xhr.setRequestHeader('Authorization', localStorage.getItem('token'))
    xhr.send(JSON.stringify(arr))
    xhr.onreadystatechange = () => {
      if (xhr.readyState == 4) {
        if (xhr.status == 200) {
          resolve(JSON.parse(xhr.responseText))
        }
      }
    }
  })
}

//模糊搜索Api 审查完毕
const searchuser = async (key) => {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    xhr.open("GET", `http://127.0.0.1:3000/users/getThatUser/${key}`, true)
    xhr.send()
    xhr.onreadystatechange = () => {
      if (xhr.readyState == 4) {
        if (xhr.status == 200) {
          resolve(JSON.parse(xhr.responseText))
        }
      }
    }
  })
}

//修改一个用户 审查完毕

const modifyuserReal = async (arr) => {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    xhr.open("PUT", "http://127.0.0.1:3000/users/modifyOneUser", true)
    xhr.setRequestHeader("content-type", "application/json")
    // xhr.setRequestHeader('Authorization', localStorage.getItem('token'))
    xhr.send(JSON.stringify(arr))
    xhr.onreadystatechange = () => {
      if (xhr.readyState == 4) {
        if (xhr.status == 200) {
          resolve(JSON.parse(xhr.responseText))
        }
      }
    }
  })
}
// }


//刷新页面的主体 审查完毕
export const reload = (newArr) => {
  document.querySelector("#rightList").innerHTML = `
<table>
<thead>
<td>编号</td><td>客户姓名</td><td>登录账号</td><td>联系电话</td><td>名下保险数量</td><td>账户密码</td><td>邀请人</td><td>操作</td>
</thead>
<tbody>

`+ newArr.map(item =>
    `
<tr>
<td>${item._id}</td>
<td>${item.userName}</td>
<td>${item.userAccount}</td>
<td>${item.userPhone}</td>
<td>未填写</td>
<td>${item.userPassWord}</td>
<td>${item.sellersId.sellersName}</td>
<td><button class="userdetail">详细信息</button>
<button class="usermodify">修改</button>
<button class="userdelete">删除</button></td>
</tr>
`
  ).join("") + `</tbody><table>`
}

//获取最新数据并刷新页面 审查完毕
export const newLoad = async () => {
  const { rows } = await getAllUsers()
  // console.log(rows);
  let newArr = rows.filter(item => {
    return !item.delete
  })
  reload(newArr)
}

//获取所有用户订单信息 审查完毕
export const getAllUsers = () => {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    xhr.open("GET", "http://127.0.0.1:3000/users/userList", true)
    xhr.send()
    xhr.onreadystatechange = () => {
      if (xhr.readyState == 4) {
        if (xhr.status == 200) {
          resolve(JSON.parse(xhr.responseText))
        }
      }
    }
  })

}
//删除一个用户订单信息  审查完毕
export const delOneUsers = (item) => {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    xhr.open("PUT", `http://127.0.0.1:3000/users/delOneUser/${item}`, true)
    xhr.send()
    xhr.onreadystatechange = () => {
      if (xhr.readyState == 4) {
        if (xhr.status == 200) {
          resolve(JSON.parse(xhr.responseText))
        }
      }
    }
  })

}

//获取指定的用户订单信息 审查完毕
export const getOneUser = (item) => {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    xhr.open("GET", `http://127.0.0.1:3000/users/getOneUser/${item}`, true)
    xhr.send()
    xhr.onreadystatechange = () => {
      if (xhr.readyState == 4) {
        if (xhr.status == 200) {
          resolve(JSON.parse(xhr.responseText))
        }
      }
    }
  })

}


